package stack;

/**
 * Created by Administrator on 2017/10/9/009.
 */
public class ArrayStack<T> implements Stack<T>{
    private final int DEFAULT_CAPACITY = 10;
    private int count;
    private T[] stack;
    public ArrayStack()
    {
        count = 0;
        stack = (T[])(new Object[DEFAULT_CAPACITY]);
    }
    public void push (T element)
    {
        if (size() == stack.length)
            expandCapacity();

        stack[count] = element;
        count++;
    }
    public String toString()
    {
        String result = "<top of stack>\n";
        for (int i=0; i < count; i++)
            result += stack[i] + "\n";
        return result+"<bottom of stack>";
    }
    private void expandCapacity()
    {
        T[] larger = (T[])(new Object[stack.length*2]);

        for (int index=0; index < stack.length; index++)
            larger[index] = stack[index];

        stack = larger;
    }
    public T pop() throws Exception
    {
        if (count==0)
            throw new Exception("PopExpection");
        else
        count--;
        T math = stack[count];
        stack[count] = null;
        return math;
    }
    public T peek() throws Exception
    {
        if (count==0)
            throw new Exception("PeekExpection");
        else
        return stack[count-1];
    }
    public boolean isEmpty()
    {
        return (count == 0);
    }
    public int size()
    {
        return count;
    }


}

